package com.demo.controller;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 卡片移动监听器，也是游戏规则
 */
public class MoveCardListener implements KeyListener {
    private static final MoveCardListener instance = new MoveCardListener();

    /**
     * a flag to control command receive
     */
    private boolean available = false;

    private MoveCardListener() {
    }

    /**
     * 卡片移动的方法“入口”
     *
     * @param direction 指示移动的方向：
     *                  MoveSolution.UP、MoveSolution.DOWN、
     *                  MoveSolution.LEFT、MoveSolution.RIGHT
     */
    private void doMove(int direction) {
        MoveSolution solution = new MoveSolution(direction);
        if (!solution.move()) {
            available = true;
        }
    }

    public void setAvailable(boolean b) {
        available = b;
    }

    public static MoveCardListener getInstance() {
        return instance;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        int direction;
        switch (keyCode) {
            case KeyEvent.VK_UP:
                direction = MoveSolution.UP;
                break;
            case KeyEvent.VK_RIGHT:
                direction = MoveSolution.RIGHT;
                break;
            case KeyEvent.VK_DOWN:
                direction = MoveSolution.DOWN;
                break;
            case KeyEvent.VK_LEFT:
                direction = MoveSolution.LEFT;
                break;
            default:
                return;
        }
        if (!available) {
            return;
        }
        // 接收指令置为“不可用”
        available = false;
        doMove(direction);
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public boolean isAvailable() {
        return available;
    }
}
